/*
 * @Author: your name
 * @Date: 2020-08-28 11:40:09
 * @LastEditTime: 2020-09-08 22:58:42
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /express/src/utils/iwencai/analyzer.ts
 */
import fs from 'fs';
import cheerio from 'cheerio';
import { Analyzer } from '../crowller';

interface queryInfoArr {
  name: string;
  url?: string | undefined;
  num: string;
}

interface CourseResult {
  time: number;
  data: queryInfoArr[];
}

interface Content {
  [propName: number]: queryInfoArr[];
}

export default class DellAnalyzer implements Analyzer {
  private static instance: DellAnalyzer;

  static getInstance() {
    if (!DellAnalyzer.instance) {
      DellAnalyzer.instance = new DellAnalyzer();
    }
    return DellAnalyzer.instance;
  }

  private getCourseInfo(html: string) {
    const $ = cheerio.load(html);
    const tableWrap = $('#tableWrap')
    const scrollOuter = tableWrap.find('div.scroll_con_outer').eq(0)
    const staticOuter = tableWrap.find('div.static_con_outer').eq(0)
    const staticTable = staticOuter.find('table.static_table').eq(0)
    const staticTr = staticTable.find('tr')
    const queryInfoArr: queryInfoArr[] = [];
    const obj = {
      index: 0,
      name: '',
      num: ''
    }
    staticTr.map((i, element) => {
      const tdRrr = $(element).find('td.item');
      const firstTd = $(element).find('td').eq(0);
      obj.index = ~~firstTd.find('div.em').eq(0).text()
      tdRrr.map((ii,el) => {
        const colNum = $(el).attr('colnum')
        if(colNum === '1') {
          // 股票名称
          const $a = $(el).find('a').eq(0)
          obj.name = $a.text()
        }else {
          // 股票代码
          const $div = $(el).find('div.em').eq(0)
          obj.num = $div.text()
        }
      })
      queryInfoArr.push(obj);
    })
console.log(queryInfoArr)
    return {
      time: new Date().getTime(),
      data: queryInfoArr
    };
  }

  private generateJsonContent(courseInfo: CourseResult, filePath: string, resetData?: Boolean) {
    let fileContent: Content = {};
    if (fs.existsSync(filePath)) {
      if(!resetData){
        fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
      }
    }
    fileContent[courseInfo.time] = courseInfo.data;
    return fileContent;
  }

  public analyze(html: string, filePath: string, resetData?: Boolean) {
    const courseInfo = this.getCourseInfo(html);
    const fileContent = this.generateJsonContent(courseInfo, filePath, resetData);
    return JSON.stringify(fileContent);
  }

  private constructor() {}
}
